from datetime import datetime
from functools import reduce

from django.db.models import Q
from django.http import JsonResponse
from rest_framework.views import APIView
from app01.Baseview import BasedAPIView
from app01 import models


class Echarts_api(BasedAPIView):
    def get(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'echart':
            return self.echart(request)

    def echart(self, request):
        page = int(request.GET.get("page", 1))  # 获取get请求传递的参数 page
        pagesize = int(request.GET.get("pagesize", 10))
        uid = request.GET.get('id', None)
        category = request.GET.get("category", None)
        add_date = request.GET.getlist("add_date[]", [])
        query = Q()
        if category is not None:
            query &= Q(category__icontains=category)
        if len(add_date) == 2:
            start_date = datetime.strptime(add_date[0], '%Y-%m-%d').date()
            end_date = datetime.strptime(add_date[1], '%Y-%m-%d').date()
            # 使用日期范围进行过滤
            query &= Q(add_date__range=(start_date, end_date))

        start_page = page * pagesize - pagesize
        end_page = page * pagesize
        #统计数据获取
        datas = models.Produce.objects.filter(query)[start_page:end_page].values()

        #按照菜品分类
        dic = {}
        #日期表
        dateDic = {}
        #菜品表
        categoryDic = {}
        for item in datas:
            key = item["category"]
            w = dic.get(key)
            if w is None:
                w = {}

            w[item["add_date"]] = item
            dic[key] = w

            #获取所有的日期
            dateDic[item["add_date"]] = ""

            #获取菜品名称
            categoryDic[key] = ""

        #日期转换为列表 然后进行排序
        dateList = []
        for key, _ in dateDic.items():
            dateList.append(key)

        #dateList = sorted(dateList, reverse=True, key=lambda date: datetime.strptime(date, '%Y-%m-%d'))
        dateList = sorted(dateList, reverse=True)

        #开始构建y轴的数据
        result = {
            "x": dateList
        }
        for dateStr in dateList:
            for key, _ in categoryDic.items():
                m = dic[key]
                data = m.get(dateStr)
                # 没有这一天的数据 默认为0
                wholesale_price = "0"
                price = "0"

                if data is not None:
                    # 有这一天的数据
                    wholesale_price = data["wholesale_price"]
                    price = data["price"]

                resultData = result.get(key)
                if resultData is None:
                    resultData = {
                        "wholesale_price": [],
                        "price": [],
                    }
                resultData["wholesale_price"].append(wholesale_price)
                resultData["price"].append(price)

                result[key] = resultData
        table = [item for item in datas]
        total = models.Produce.objects.filter(query).count()
        data = {
            "code": 200,
            "total": total,
            "msg": "查询成功",
            "data": result,
            "table": table
        }
        return JsonResponse(data)
